package com.hzcx.app.simplechat.ui.chat;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.chat.adapter.ChatEmojiLikeAdapter;
import com.hzcx.app.simplechat.dao.ChatEmojiLikeDao;
import com.hzcx.app.simplechat.ui.chat.event.ChatEmojiLikeEvent;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.photo.PhotoUtil;
import com.hzcx.app.simplechat.view.autogridview.PhotoLoader;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;
import org.litepal.crud.callback.UpdateOrDeleteCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import indi.liyi.viewer.ImageViewer;

/**
 * 自定义表情管理
 */
public class ChatEmojiManagerActivity extends BaseActivity implements OnResultCallbackListener<LocalMedia> {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.tv_select_num)
    TextView tvSelectNum;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.tv_move)
    TextView tvMove;
    @BindView(R.id.cons_bottom)
    ConstraintLayout consBottom;
    @BindView(R.id.rv_emoji)
    RecyclerView rvEmoji;
    @BindView(R.id.imageViewer)
    ImageViewer imageViewer;

    private List<ChatEmojiLikeDao> emojiData;
    private ChatEmojiLikeAdapter likeAdapter;
    private boolean isManager = false;
    private List<ChatEmojiLikeDao> selectData;
    private int num;

    @Override
    public int getLayout() {
        return R.layout.activity_chat_emoji_manager;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {

        imageViewer.imageLoader(new PhotoLoader());

        tvTitle.setText("表情管理");
        tvTitleRight.setText("管理");

        selectData = new ArrayList<>();
        emojiData = new ArrayList<>();
        likeAdapter = new ChatEmojiLikeAdapter(emojiData);
        rvEmoji.setLayoutManager(new GridLayoutManager(this, 5));
        rvEmoji.setAdapter(likeAdapter);
    }

    @Override
    public void initData() {

        emojiData.add(new ChatEmojiLikeDao(null, 0));

        LitePal.order("createTime desc").findAsync(ChatEmojiLikeDao.class).listen(list -> {
            if (list == null || list.size() <= 0) {
                return;
            }
            emojiData.addAll(list);
            likeAdapter.notifyDataSetChanged();
            tvTitle.setText("表情管理(" + (emojiData.size() - 1) + ")");
        });

        likeAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (!isManager) {
                if (position == 0) {
                    PhotoUtil.showPhoto(this, PictureMimeType.ofImage(), PictureConfig.SINGLE, true, false, null, this);
                } else {
                    List<String> imgs = new ArrayList<>();
                    for (ChatEmojiLikeDao dao : emojiData) {
                        imgs.add(dao.getPath());
                    }
                    imageViewer.overlayStatusBar(true)
                            .imageData(imgs)
                            .bindViewGroup(rvEmoji)
                            .watch(position);
                }
            } else {
                if (emojiData.get(position).isSelect()) {
                    num--;
                } else {
                    num++;
                }
                emojiData.get(position).setSelect(!emojiData.get(position).isSelect());
                likeAdapter.notifyDataSetChanged();
                tvSelectNum.setText("已选择" + num + "个");
            }
        });

    }

    @OnClick({R.id.tv_title_right, R.id.tv_delete,R.id.tv_move})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_title_right:
                if (!isManager) {
                    tvTitleRight.setText("完成");
                    consBottom.setVisibility(View.VISIBLE);
                    emojiData.remove(0);
                    likeAdapter.setManager(true);
                    likeAdapter.notifyDataSetChanged();
                } else {
                    tvTitleRight.setText("管理");
                    consBottom.setVisibility(View.GONE);
                    emojiData.add(0, new ChatEmojiLikeDao(null, 0));
                    likeAdapter.setManager(false);
                    likeAdapter.notifyDataSetChanged();
                }
                isManager = !isManager;
                break;

            case R.id.tv_delete: // 删除
                if (num <= 0) {
                    showError("请选择要删除的表情");
                    return;
                }
                deleteEmoji();
                break;

            case R.id.tv_move: // 移动到最前面
                moveEmoji();
                break;
        }
    }

    /**
     * 图片选择返回
     *
     * @param result
     */
    @Override
    public void onResult(List<LocalMedia> result) {
        ChatEmojiLikeDao likeDao = new ChatEmojiLikeDao(PhotoUtil.getPath(result.get(0)), System.currentTimeMillis());
        emojiData.add(1, likeDao);
        likeAdapter.notifyDataSetChanged();
        tvTitle.setText("表情管理(" + (emojiData.size() - 1) + ")");
        likeDao.saveAsync().listen(success -> EventBus.getDefault().post(new ChatEmojiLikeEvent()));
    }

    @Override
    public void onCancel() {

    }

    /**
     * 删除表情
     */
    private void deleteEmoji() {
        if (selectData == null) {
            return;
        }
        for (ChatEmojiLikeDao dao : emojiData) {
            if (dao.isSelect()) {
                selectData.add(dao);
            }
        }
        if (selectData.size() <= 0) {
            return;
        }
        for (ChatEmojiLikeDao dao : selectData) {
            dao.delete();
            emojiData.remove(dao);
        }
        likeAdapter.notifyDataSetChanged();
        tvTitle.setText("表情管理(" + (emojiData.size()) + ")");
        num = 0;
        tvSelectNum.setText("已选择" + num + "个");
        EventBus.getDefault().post(new ChatEmojiLikeEvent());
    }

    /**
     * 移动表情位置
     */
    private void moveEmoji() {
        if (selectData == null) {
            return;
        }
        for (ChatEmojiLikeDao dao : emojiData) {
            if (dao.isSelect()) {
                selectData.add(dao);
            }
        }
        if (selectData.size() <= 0) {
            return;
        }
        for (ChatEmojiLikeDao dao : selectData) {
            dao.setSelect(false);
            dao.setCreateTime(System.currentTimeMillis());
            dao.save();
        }
        num = 0;
        tvSelectNum.setText("已选择" + num + "个");
        emojiData.clear();
        LitePal.order("createTime desc").findAsync(ChatEmojiLikeDao.class).listen(list -> {
            if (list == null || list.size() <= 0) {
                return;
            }
            emojiData.addAll(list);
            likeAdapter.notifyDataSetChanged();
            tvTitle.setText("表情管理(" + (emojiData.size() - 1) + ")");
        });
        EventBus.getDefault().post(new ChatEmojiLikeEvent());
    }
}
